<template>
  <div>
    <p class="desc-text mb20">{{ $t("form.public.addExtensionAttributes") }}</p>
    <div class="mb10">
      <el-button
        type="primary"
        size="default"
        icon="ele-Plus"
        @click="openBatchGenerateDialog"
      >
        {{ $t("form.public.batchGen") }}
      </el-button>
      <el-button
        type="primary"
        size="default"
        icon="ele-Download"
        @click="handleDownloadQrcode"
      >
        {{ $t("form.public.exportQrcode") }}
      </el-button>
      <el-button
        type="danger"
        icon="ele-Delete"
        size="default"
        @click="handleDeleteLinkExt(null)"
        :disabled="!ids.length"
      >
        {{ $t("common.delete") }}
      </el-button>
    </div>
    <el-divider />
    <div
      v-if="publishStatus"
      class="ext-value-list-wrap"
    >
      <el-table
        :data="linkExtList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          align="center"
          type="selection"
          width="50"
        />
        <el-table-column
          prop="extValue"
          :label="$t('form.public.extensionValue')"
        ></el-table-column>
        <el-table-column :label="$t('common.operation')">
          <template #default="scope">
            <el-button-group
              class="ml4"
              size="default"
            >
              <el-button
                type="primary"
                v-copyText="getRowUrl(scope.row)"
                icon="ele-CopyDocument"
              >
                {{ $t("form.public.copy") }}
              </el-button>
              <el-button
                type="primary"
                icon="ele-Edit"
                @click="handleOpenLinkExt(scope.row)"
              >
                {{ $t("form.public.open") }}
              </el-button>
              <el-button
                type="primary"
                icon="ele-Edit"
                @click="handleDeleteLinkExt(scope.row)"
              >
                {{ $t("common.delete") }}
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        size="default"
        v-if="linkExtTotal > 5"
        v-model:limit="extValQueryParams.size"
        v-model:page="extValQueryParams.current"
        :total="linkExtTotal"
        @pagination="getFormLinkExtList"
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="$t('form.public.batchGen')"
    >
      <el-input
        type="textarea"
        v-model="batchExtValues"
        :placeholder="$t('form.public.extInputPlaceholder')"
        :rows="10"
      ></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ $t("common.cancel") }}</el-button>
          <el-button
            type="primary"
            :loading="batchExtLoading"
            @click="handleBatchGenerate"
          >
            {{ $t("common.confirm") }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="ExtValueList">
import {
  batchSaveFormLinkExtRequest,
  deleteFormLinkExtRequest,
  exportFormLinkExtQrcode,
  getFormLinkExtListRequest,
  saveFormLinkExtRequest
} from "@/api/project/publish";
import { i18n } from "@/i18n";
import { useRoute } from "vue-router";
import { MessageBoxUtil, MessageUtil } from "@/utils/messageUtil";
import { onMounted, ref } from "vue";
import { getBaseUrlPath } from "@/utils/auth";
import { download } from "@/utils/tduck";

const props = defineProps({
  publishStatus: {
    type: Boolean,
    default: false
  }
});

const formKey = ref("");
const extValue = ref("");
const linkExtList = ref<any[]>([]);
const linkExtTotal = ref(0);
// 查询参数
const extValQueryParams = ref({
  current: 1,
  size: 5,
  formKey: ""
});

const dialogVisible = ref(false);
const batchExtValues = ref("");

const getFormLinkExtList = () => {
  extValQueryParams.value.formKey = formKey.value;
  getFormLinkExtListRequest(extValQueryParams.value).then(res => {
    linkExtList.value = res.data.records;
    linkExtTotal.value = res.data.total;
  });
};

const handleSaveLinkExt = () => {
  if (!extValue.value) {
    MessageUtil.warning(i18n.global.t("form.public.enterExtensionName"));
    return;
  }
  if (!props.publishStatus) {
    MessageUtil.error(i18n.global.t("form.public.generateFailed"));
    return;
  }
  saveFormLinkExtRequest({
    formKey: formKey.value,
    extValue: extValue.value
  }).then(() => {
    MessageUtil.success(i18n.global.t("formI18n.all.success"));
    extValue.value = "";
    getFormLinkExtList();
  });
};

const handleDeleteLinkExt = (row: any) => {
  MessageBoxUtil.confirm(`${i18n.global.t("common.deleteConfirm")}`, () => {
    const idList = row ? [row.id] : ids.value;
    deleteFormLinkExtRequest({
      ids: idList,
      key: formKey.value
    }).then(() => {
      MessageUtil.success(i18n.global.t("formI18n.all.success"));
      getFormLinkExtList();
    });
  });
};

const createDataLink = ref("");

const route = useRoute();

onMounted(() => {
  formKey.value = route.query.key as string;
  let url = getBaseUrlPath();
  createDataLink.value = `${url}/s/${formKey.value}`;
  getFormLinkExtList();
});

const openBatchGenerateDialog = () => {
  batchExtValues.value = "";
  dialogVisible.value = true;
};

const batchExtLoading = ref(false);

const handleBatchGenerate = async () => {
  batchExtLoading.value = true;
  const extValuesArray = batchExtValues.value
    .split("\n")
    .map(value => value.trim())
    .filter(value => value);
  if (extValuesArray.length === 0) {
    MessageUtil.warning(i18n.global.t("form.public.enterExtensionName"));
    return;
  }
  try {
    const res = await batchSaveFormLinkExtRequest({
      formKey: formKey.value,
      extList: extValuesArray
    });
    if (res.msg) {
      MessageUtil.warning(res.msg);
    } else {
      MessageUtil.success(i18n.global.t("common.saveSuccess"));
    }
    dialogVisible.value = false;
    getFormLinkExtList(); // 刷新扩展值列表
  } catch (error) {
    console.log(error);
    MessageUtil.error(i18n.global.t("form.public.generateFailed"));
  } finally {
    batchExtLoading.value = false;
  }
};

const getRowUrl = (row: any) => {
  return `${createDataLink.value}?ext=${row.extValue}`;
};

const handleOpenLinkExt = (row: any) => {
  const url = getRowUrl(row);
  window.open(url, "_blank");
};

const ids = ref<number[]>([]);
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.id);
};

const handleDownloadQrcode = () => {
  exportFormLinkExtQrcode({
    formKey: formKey.value
  }).then((res: any) => {
    download(res, i18n.global.t("form.public.extNameWord", { no: new Date().getTime() }), ".docx");
  });
};
</script>
<style lang="scss" scoped>
.delete-icon {
  cursor: pointer;
  z-index: 999;
}

.ext-label {
  color: #303133;
}
</style>
